<%--
  Created by IntelliJ IDEA.
  User: leixiaolong
  Date: 2018/9/20
  Time: 下午5:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="/WEB-INF/include.jsp" %>

<html>
<head>
    <title>采购单编辑</title>
    <link rel="stylesheet" href="/static/css/rpt-condition.css" media="all" type="text/css">

    <style>
        .layui-form-label {
            width: 160px !important;
        }
    </style>

    <style>
        /* 防止下拉框的下拉列表被隐藏---必须设置--- */
        .layui-table-cell {
            overflow: visible !important;
        }

        /* 使得下拉框与单元格刚好合适 */
        td .layui-form-select {
            /*margin-top: -10px;*/
            /*margin-left: -15px;*/
            /*margin-right: -15px;*/
            /*solid: #d2d2d2;*/
            /*border: 1px;*/
        }

        /* 设置下拉框的高度与表格单元相同 */
        .layui-input, .layui-select, .layui-textarea {
            height: 30px !important;
        }
    </style>

    <style>
        .col-select-lg {
            margin-top: 10px;
            /*height: 30px;*/
            width: 300px;
            min-width: 200px;
            max-width: 600px;
        }

        .layui-input-inline {
            min-width: 300px;
            max-width: 600px;
        }
    </style>
</head>
<body class="layui-bg-gray">
<div class="layui-row layui-col-space10" style="margin: 10px; background-color: white">
    <div class="layui-container">
        <div class="layui-row layui-form">
            <div class="layui-col-md6 layui-hide">
                <div class="layui-form-item">
                    <label class="layui-form-label ">采购单id：</label>
                    <input type="text" id="cred_id" class="layui-input-inline dom-add-input">
                </div>
            </div>
            <div class="layui-col-md6 ">
                <div class="layui-form-item">
                    <label class="layui-form-label ">供货商名称：</label>
                    <div class="layui-input-inline">
                        <select id="supp_name" class="layui-form-select  col-select-lg">
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">采购类型：</label>
                    <div class="layui-input-inline">
                        <select id="purc_type" class="col-select-lg">
                            <option value="1" selected>现采</option>
                            <option value="2">赊购</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">收货仓库：</label>
                    <div class="layui-input-inline">
                        <select id="stor_code" class="layui-form-select col-select-lg">
                            <option value=1 selected>仓库1</option>
                            <option value=2>仓库2</option>
                        </select>
                    </div>
                </div>
            </div>
            <%--<div class="layui-col-md6">--%>
                <%--<div class="layui-form-item">--%>
                    <%--<label class="layui-form-label">源单据类型：</label>--%>
                    <%--<div class="layui-input-inline">--%>
                        <%--<select id="bill_type" class="layui-form-select col-select-lg">--%>
                            <%--<option value=1 selected>类型1</option>--%>
                            <%--<option value=2>类型2</option>--%>
                        <%--</select>--%>
                    <%--</div>--%>
                <%--</div>--%>
            <%--</div>--%>
            <div class="layui-col-md6">
                <div class="layui-form-item">

                    <label class="layui-form-label">源单据id：</label>
                    <input type="text" id="bill_id" class="layui-input-inline dom-add-input">
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">摘要：</label>
                    <input type="text" id="digest" class="layui-input-inline dom-add-input">
                </div>
            </div>
        </div>
    </div>
</div>
<div style="margin: 10px; background-color: white;">
    <table class="layui-hide" id="tab_purc_cred_edit" lay-filter="filter-purc-cred-edit"></table>
</div>

<div class="layui-btn-container" style="float: right; margin-right: 10%">
    <button class="layui-btn layui-btn-normal layui-btn-warm" lay-submit data-type="submit">提交</button>
    <button class="layui-btn layui-btn-normal layui-btn-warm" lay-submit data-type="cancel">取消</button>
</div>
</body>

<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/form-select.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/table-data.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/utils/tax-math.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/utils/base-data.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/utils/base-math.js"></script>

<script type="text/html" id="toolbarAdd">
    <div class="layui-btn-group" style="float: right; margin-right: 10px;">
        <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="add">新增</button>
    </div>
</script>

<script type="text/html" id="templateSelect">
    <select id='select_{{d.id}}' layui-filter="selectfish">
        <option value="" selected>请选择</option>
    </select>
</script>

<script type="text/html" id="tabRowBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/comm-data.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/form-select.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/form-date.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/utils/moment.js"></script>
<script>
    var recordNum = 0;
    var taxRate = 0;
    var gooddata = [];

    async function initTable() {
        var res = new Promise(function (resolve, reject) {
            layui.use(["element", "form", "layer", "table", "jquery", "laydate"], function () {
                var element = layui.element, layer = layui.layer, table = layui.table, $ = layui.jquery;
                var form = layui.form, laydate = layui.laydate;



                table.set({
                    limit: 50
                });
                var tableIns = table.render({
                    id: 'tab_purc_cred_edit',
                    elem: '#tab_purc_cred_edit',
                    toolbar: '#toolbarAdd',
                    defaultToolbar: [],
                    cellMinWidth: 90,
                    // even: true, //隔行背景
                    height: 'full-240',
                    cols: [[
                        {
                            field: 'seqNo', title: '序号', align: 'center'
                        },
                        {field: 'goodCode', title: '商品编码', align: 'center', hide: true},
                        {
                            field: 'goodName', title: '商品名称', minWidth: 140, templet: function (d) {
                                return loadGoodSelect(d.seqNo, gooddata, d.goodCode);
                            }, align: 'center'
                        },
                        {field: 'varietyCode', title: '品种编码', align: 'center', hide: true},
                        {field: 'varietyName', title: '品种名称', align: 'center', hide: true},
                        {field: 'standardName', title: '商品规格', align: 'center'},
                        {field: 'unit', title: '商品单位', align: 'center'},
                        {
                            field: 'inTaxRate', title: '商品进项税率', align: 'center', templet: function (d) {
                                return getFloat(d.inTaxRate);
                            }
                        },
                        {
                            field: 'price', title: '商品价格', edit: true, align: 'center', templet: function (d) {
                                return getFloat(d.price);
                            }
                        },
                        {
                            field: 'noTaxPrice', title: '商品不含税价格', align: 'center', templet: function (d) {
                                return computeNoTaxPrice(d.price, d.inTaxRate);
                            }
                        },
                        {
                            field: 'amount', title: '商品数量', edit: true, align: 'center', templet: function (d) {
                                return getFloat(d.amount);
                            }
                        },
                        {
                            field: 'bal', title: '商品金额', align: 'center', templet: function (d) {
                                if (typeof(d.price) == 'undefined' || typeof(d.amount) == 'undefined') {
                                    return 0;
                                }
                                return getFloat(d.price * d.amount);
                            }
                        },
                        {
                            field: 'noTaxBal', title: '商品不含税金额', align: 'center', templet: function (d) {
                                if (typeof(d.amount) == 'undefined') {
                                    return 0;
                                }
                                if (typeof(d.amount) == "string" && (d.amount == null || d.amount.trim().length === 0)) {
                                    return 0;
                                }

                                return round((getFloat(d.price) - computeNoTaxPrice(d.price, d.inTaxRate)) * d.amount, 2);
                            }
                        },
                        {
                            field: 'estInTax', title: '预估进项税', align: 'center', templet: function (d) {
                                if (typeof(d.amount) == 'undefined') {
                                    return 0;
                                }
                                if (typeof(d.amount) == "string" && (d.amount == null || d.amount.trim().length === 0)) {
                                    return 0;
                                }
                                return round((getFloat(d.price) - computeNoTaxPrice(d.price, d.inTaxRate)) * d.amount, 2);
                            }
                        },
                        {field: 'digest', title: '摘要', align: 'center', edit: true},
                        {field: 'operator', title: '操作', fixed: 'right', templet: '#tabRowBar'}]],
                    done: function () {
                        console.log("渲染表格 over");
                        form.render();
                    },
                    page: false
                });

                /**
                 * 监听表头工具bar事件
                 */
                table.on('toolbar', function (obj) {
                    switch (obj.event) {
                        case 'add':
                            layer.msg('添加');
                            debugger
                            var newdata = table.cache["tab_purc_cred_edit"];
                            if (newdata == null || newdata == 'undefined') {
                                newdata = [];
                            }

                            var newline = {};
                            recordNum = newdata.length;
                            newline['seqNo'] = ++recordNum;

                            // newdata.unshift(newline);//左侧加入
                            newdata.push(newline);//右侧加入
                            table.reload('tab_purc_cred_edit', {
                                url: null,
                                limit: 50,
                                data: newdata
                            });

                            loadGoodSelect(recordNum, gooddata);
                            form.render('select');
                            break;
                        case 'del':
                            layer.msg('删除');
                            break;
                        case 'update':
                            layer.msg('编辑');
                            break;
                    }
                });

                /**
                 * 监听表行工具bar事件
                 */
                table.on('tool', function (obj) {
                    //获得当前行数据
                    var rowdata = obj.data;
                    var layEvent = obj.event;//获得当前行事件
                    var tr = obj.tr;//获得当前行tr的dom对象

                    switch (layEvent) {
                        case 'del':
                            layer.confirm("是否删除本条记录", {icon: 3}, function (index) {
                                obj.del();
                                layer.close(index);
                            });
                            break;
                        default:
                            layer.msg("请等待功能开放");
                            break;
                    }

                    //同步更新缓存对应的值
                    // obj.update({username:'123', title: 'xxx'});
                });

                /**
                 * 监听select下拉框事件
                 */
                form.on('select', async function (data) {
                    //监听数据处理
                    var goodCode = data.value;

                    //获取当前行记录
                    var rowData = await getRowItemBySeqNo("tab_purc_cred_edit", data.elem.id.substring(data.elem.id.indexOf("_") + 1, data.elem.id.length))
                        .then(function (result) {
                            return result;
                        });

                    //获取商品信息
                    var goodInfo = getGoodInfoById(goodCode);

                    //获取税率
                    if (taxRate == null || taxRate <= 0) {
                        taxRate = getTaxRate();
                    }
                    //get商品信息 goodInfo
                    var goodData = {
                        "seqNo": rowData.seqNo,
                        "goodCode": data.value,
                        "varietyCode": goodInfo.varietyCode,
                        "inTaxRate": taxRate,
                        "varietyName": goodInfo.varietyName,
                        "standardName": goodInfo.standardName,
                        "unit": goodInfo.unit,
                        "inTaxRate": taxRate
                    };

                    var isClear = false;
                    if (data.value == null || data.value.trim().length === 0) {
                        var rowid = goodData.seqNo;
                        goodData = {};
                        goodData['seqNo'] = rowid;
                        isClear = true;
                    }

                    //对商品信息更新赋值
                    updateRowItem("tab_purc_cred_edit", goodData, isClear);
                });

                /**
                 * 监听编辑单元格事件
                 */
                table.on('edit', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
                    var data = obj.data;

                    obj.update(data);
                    form.render('select');
                });

                /**
                 * 监听按钮提交事件
                 * @type {{submit: active.confirm, cancel: active.cancel}}
                 */
                var active = {
                    submit: function confirm() {
                        var data = table.cache["tab_purc_cred_edit"];
                        var newdata = trimAllArray(data);

                        var request = {
                            "credId": $('#cred_id').val(),
                            "suppCode": $('#supp_name').find('option:selected').val(),
                            "suppAbbrName": $('#supp_name').find('option:selected').text(),
                            "purcType": $('#purc_type').find('option:selected').val(),
                            "storCode": $('#stor_code').find('option:selected').val(),
                            "deliDate": $('#deli_date').val(),
                            // "sourBillType": $('#bill_type').find('option:selected').val(),
                            "sourBillId": $('#bill_id').val(),
                            "digest": $('#digest').val(),
                            "credDetailInfos": newdata
                        };
                        var reqBody = JSON.stringify(request);

                        $.ajax({
                            type: "POST",
                            url: "/purc/cred/editPurcCred",
                            contentType: 'application/json',
                            dataType: 'json',//服务端返回数据类型
                            data: reqBody,
                            async: false,
                            success: function (data) {
                                if (data.rspCode == 'RSP000000') {
                                    layer.msg("录入采购单成功,订单编号:" + data.data);
                                    var index = parent.layer.getFrameIndex(window.name);
                                    parent.layer.close(index);

                                    // parent.layui.table.reload("tab_cred", {});
                                    parent.reloadTable();
                                    return;
                                } else {
                                    layer.msg("录入采购单失败:" + data.rspMsg);
                                    return;
                                }
                            },
                            error: function (data) {
                                console.log("系统异常:" + data);
                                layer.msg("系统异常,请联系管理员");
                                return;
                            }
                        });
                    },
                    cancel: function cancel() {
                        layer.msg("关闭弹出订单录入");
                        var index = parent.layer.getFrameIndex(window.name); //获取当前窗体索引

                        parent.layer.close(index);
                        // parent.layui.table.reload("tab_cred", {});
                        // parent.reloadTable();
                        return;
                    }
                };
                form.on('submit', function (data) {
                    var elem = data.elem;
                    active[$(this).data("type")].call(this, elem);
                });

                resolve(tableIns);
            });
        }).then(function (result) {
            console.log("初始化table完成", result);
            return result;
        });
        return res;
    }

    var syncInit = async (rowdata) => {
        //初始记录序号为0
        recordNum = 0;

        var res = await syncInitModule();
        console.log("同步初始模块完成", res);

        await initTable();

        layui.use(["form", "jquery", "table"], function () {
            var form = layui.form, table = layui.table, $ = layui.jquery;

            let whereData = {credId: rowdata.credId};

            table.reload('tab_purc_cred_edit', {
                limit: 50,
                url: '/purc/cred/getPurcCredDetailList',
                where: whereData
            });

            console.log("init data:", JSON.stringify(rowdata));
            $('#cred_id').val(rowdata.credId);
            $('#supp_name').val(rowdata.suppCode);
            $('#purc_type').val(rowdata.purcType);
            $('#stor_code').val(rowdata.storCode);
            // $('#bill_type').val(rowdata.sourBillType);
            $('#bill_id').val(rowdata.sourBillId);
            $('#digest').val(rowdata.digest);

            form.render();
        });

        async function syncInitModule() {
            //初始化获取商品信息
            loadGoodData();

            async function loadGoodData() {
                gooddata = await getGoodsInfo();
            }

            //加载商品信息
            var resGood = getGoodsInfo(gooddata);
            //初始供货商下拉框
            var resSupp = initSuppInfoSelect('supp_name');
            //初始仓库下拉框
            var resStor = initStorSelect('stor_code');

            var paramSourcBillType = {
                sysCode: 21,
                code: 1
            }
            //初始源单据类型
            // var resBillType = initCodeTableSelect('bill_type', '/base/getSysCodeList', paramSourcBillType);
            var paramPurcType = {code: 1};
            //初始采购类型
            var resPurcType = initCodeTableSelect('purc_type', '/base/getPurcTypeList', paramPurcType);

            var result = await Promise.all([resGood, resSupp, resStor]);
            result.forEach(function (currval, index, arr) {
                console.log(currval);
            });

            return "done";
        }
    };
</script>
</html>
